/**
 @Name: user
 */
layui.define(['laypage', 'tbynet'], function(exports) {
	var $ = layui.$
	,form = layui.form
	,layer = layui.layer
	,laytpl = layui.laytpl
	,laypage = layui.laypage
	,tbynet = layui.tbynet;
	
	form.on('radio(visibility)', function(data){
		"public" != data.value ? ($("#sticky").prop("checked", false), $("#sticky-span").hide()) : $("#sticky-span").show(), 
		 "password" != data.value ? $("#password-span").hide() : ($("#password-span").show(), $("#sticky").prop("checked", false)),
		form.render('checkbox')
	});
	
  	$(".edit-visibility").click(function(e) {
        e.preventDefault(), 
        $("#post-visibility-select").is(":hidden") && ($("#post-visibility-select").slideDown("fast", function() {
        	$("#post-visibility-select").find('input[type="radio"]').first().focus()
        }), 
        $(this).hide())
    });
  	
  	$("#post-visibility-select").find(".cancel-post-visibility").click(function(e) {
  		$("#post-visibility-select").slideUp("fast"), 
        $("#visibility-radio-" + $("#hidden-post-visibility").val()).prop("checked", !0), 
        $("#post_password").val($("#hidden-post-password").val()), 
        $("#sticky").prop("checked", $("#hidden-post-sticky").prop("checked")), 
//        $("#post-visibility-display").html(new Date($("#hidden_aa").val(), $("#hidden_mm").val() - 1, $("#hidden_jj").val(), $("#hidden_hh").val(), $("#hidden_mn").val())), 
        $(".edit-visibility").show().focus(), 
        //g(), 
        e.preventDefault()
    });
  	$("#post-visibility-select").find(".save-post-visibility").click(function(e) {
  		$("#post-visibility-select").slideUp("fast"), 
        $(".edit-visibility").show().focus(), 
        //g(), 
        "public" != $("#post-visibility-select").find("input:radio:checked").val() && $("#sticky").prop("checked", !1), 
        h = $("#sticky").prop("checked") ? "Sticky" : "", 
        $("#post-visibility-display").html(postL10n[$("#post-visibility-select").find("input:radio:checked").val() + h]), 
        e.preventDefault()
    });
  	
  	$("#timestampdiv").siblings("a.edit-timestamp").click(function(e) {
  		$("#timestampdiv").is(":hidden") && ($("#timestampdiv").slideDown("fast", function() {
            $("input, select", $("#timestampdiv").find(".timestamp-wrap")).first().focus()
        }), $(this).hide()), 
        e.preventDefault()
    });
  	$("#timestampdiv").find(".cancel-timestamp").click(function(e) {
  		$("#timestampdiv").slideUp("fast").siblings("a.edit-timestamp").show().focus(), 
        e.preventDefault()
    });
  	$("#timestampdiv").find(".save-timestamp").click(function(e) {
  		$("#timestampdiv").slideUp("fast"), 
  		$("#timestampdiv").siblings("a.edit-timestamp").show().focus(), 
        e.preventDefault()
    });
  	$("#post-status-select").siblings("a.edit-post-status").click(function(e) {
  		$("#post-status-select").is(":hidden") && ($("#post-status-select").slideDown("fast", function() {
  			$("#post-status-select").find("select").focus()
        }), 
        $(this).hide()), 
        e.preventDefault()
    });
  	$("#post-status-select").find(".save-post-status").click(function(e) {
  		$("#post-status-select").slideUp("fast").siblings("a.edit-post-status").show().focus(), 
        e.preventDefault()
    });
  	$("#post-status-select").find(".cancel-post-status").click(function(e) {
  		$("#post-status-select").slideUp("fast").siblings("a.edit-post-status").show().focus(), 
        $("#post_status").val($("#hidden_post_status").val()), 
        e.preventDefault()
    });
  	
  	$('#category-add-toggle').on('click', function(){
  		if($('#category-add').is(':hidden')){
  			$('#category-add').show();
  		} else {
  			$('#category-add').hide();
  		}
  	});
  	
  	$('#link-post_tag').on('click', function(){
  		if($('#tagcloud-post_tag').is(':hidden')){
  			$('#tagcloud-post_tag').show();
  		} else {
  			$('#tagcloud-post_tag').hide();
  		}
  	});
  	
  	$('#new-tag-post_tag').on('focus', function(e){
  		showTag($(this).val());
  	});
  	$('#new-tag-post_tag').on('keyup', function(e){
  		showTag($(this).val());
  	});
  	$('#taglist').on('click', 'li', function(e){
  		var tag = $(this).text();
  		var str = $('#new-tag-post_tag').val();
  		
  		var array = str.split('、');
  		var q = array.pop();
  		
  		if(str.indexOf(tag) == -1 || q == tag) {
  			array.push(tag);
  		}
  		
  		$('#new-tag-post_tag').val(array.join('、') + '、');
  		hideTag();
  	});
  	$('#tagadd').on('click', function(e){
  		var newtag = $('#new-tag-post_tag').val();
  		if(null == newtag || '' == newtag) {
  			return;
  		}
  		$('#new-tag-post_tag').val('');
  		
  		$('#tax-tag-post_tag').val($('#tax-tag-post_tag').val() + newtag);
  		var taxtag = $('#tax-tag-post_tag').val();
  		
  		var html = '';
  		var array = taxtag.split('、');
  		for(var i in array) {
  			var tag = array[i];
  			if(null == tag || '' == tag) {
  				continue;
  			}
  			html += '<li data="'+ tag +'">\
				<button type="button" class="ntdelbutton">\
					<span class="layui-icon layui-icon-close-fill" style="color:#0073aa;"></span>\
					<span class="screen-reader-text">移除项目：'+ tag +'</span>\
				</button>\
				&nbsp;'+ tag +'\
			</li>';
  		}
  		$('.tagchecklist').html(html);
  	});
  	$('.tagchecklist').on('click', 'li', function(){
  		var tag = $(this).attr('data');
  		var taxtag = $('#tax-tag-post_tag').val();
  		var array = taxtag.split('、');
  		array = $.grep(array, function(value) {
  			 return value != tag;
  		});
  		$('#tax-tag-post_tag').val(array.join('、') + '、');
  		$(this).remove();
  	});
  	
  	function showTag(str){
  		if(null == str || '' == str || 2 > str.length) {
  			hideTag();
  			return;
  		}
  		
  		var q = str.substring(str.lastIndexOf('、') + 1);
  		if(null == q || '' == q || 2 > q.length) {
  			hideTag();
  			return;
  		}
  		
  		if(!$('#new-tag-post_tag').hasClass('ui-autocomplete-loading')){
  			$('#new-tag-post_tag').addClass('ui-autocomplete-loading');
  		}
  		
  		tbynet.ajax('/admin/tag/search', {q: q}, function(res){
  			setInterval(function(){
  				if($('#new-tag-post_tag').hasClass('ui-autocomplete-loading')){
  	  				$('#new-tag-post_tag').removeClass('ui-autocomplete-loading');
  	  			}
  			}, 1000);
  			
  			if(res.data.totalRow == 0) {
  				hideTag();
  			} else {
  				var html = '';
  	  			layui.each(res.data.list, function(index, item){
  	  				html += '<li class="ui-menu-item" tabindex="-1">'+ item.name +'</li>';
  	  			});
  	  			$('#taglist').html(html);
  	  			
  	  			$('#taglist').slideDown("fast");
  	  			$("body").bind("mousedown", onBodyDown);
  			}
  		});
  	}
  	function hideTag(){
  		$('#taglist').fadeOut("fast");
  		$("body").unbind("mousedown", onBodyDown);
  	}
  	function onBodyDown(event) {
		if (!(event.target.id == "new-tag-post_tag" || event.target.id == "taglist" || $(event.target).parents("#taglist").length>0)) {
			hideTag();
		}
	}
  	
  	$('body').on('click', '#set-post-thumbnail', function(){
  		layer.open({
  			type: 2,
  			title: '特色图片',
  			skin: 'finder',
  			shadeClose: true,
  			shade: 0.8,
  			area: ['90%', '90%'],
  			content: '/admin/attachment/finder' //iframe的url
  		});
  	});
  	
	//表单提交返回成功后才执行这个方法
	tbynet.form['/admin/post/save'] = function(data, required, res){
		layer.msg(res.msg, {
			offset: '15px'
			,icon: 1
			,time: 1000
		}, function(){
			location.href = '/admin/post';
		});
	}; 
	
	tbynet.form['/admin/post/update'] = function(data, required, res){
		layer.msg(res.msg, {
			offset: '15px'
			,icon: 1
			,time: 1000
		}, function(){
			location.href = '/admin/post';
		});
	};
	
    var gather = {
    	search: function(curr, q) {
    		search(curr, q);
    	}
    	,trash: function(id) {
    		tbynet.ajax('/admin/post/trash', {post: id}, function(res){
    			layer.msg(res.msg, {
    				offset: '15px'
    				,icon: 1
    				,time: 1000
    			}, function(){
    				location.href = '/admin/post';
    			});
    		});
    	}
    };
    
    function search(curr, q){
    	if($('#post-page-tpl').length == 0) {
    		return;
    	}
    	
		tbynet.ajax('/admin/post/search', {page: curr || 1, q: q || $('#post-search-input').val()}, function(res){
			
			if(res.data.totalRow == 0) {
				$('table tbody').html('<tr><td colspan="7">找不到文章。</td></tr>');
				$('.tablenav').hide();
			} else {
				laytpl($('#post-page-tpl').html()).render(res.data.list, function(html){
					$('table tbody').html(html);
				});
			}
			
			laypage.render({elem: $('.tablenav-pages'), count: res.data.totalRow, limit: res.data.pageSize, curr: curr || 1, layout: ['count', 'prev', 'page', 'next'], jump: function(obj, first){
				if(!first){
			        search(obj.curr, q);
				}
			}});
			
			form.render();
		}, "json");
	};
	
	search();
	

    exports('post', gather);
});